package org.jeecg.modules.demo.ysd.controller;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class WxDataDecryptor {

    /**
     * 解密微信小程序 encryptedData
     *
     * @param encryptedData 加密的用户数据
     * @param sessionKey 会话密钥
     * @param iv 加密算法的初始向量
     * @return 解密后的JSON字符串
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            // Base64解码
            byte[] dataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            // 初始化密钥和参数
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            // 初始化密码器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // 执行解密
            byte[] resultBytes = cipher.doFinal(dataBytes);

            // 返回解密结果
            return new String(resultBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密微信数据失败", e);
        }
    }

    /**
     * 验证解密后的数据
     *
     * @param decryptedData 解密后的JSON字符串
     * @param appId 小程序appId
     * @return 验证是否有效
     */
    public static boolean verifyData(String decryptedData, String appId) {
        try {
            JSONObject json = JSONObject.parseObject(decryptedData);
            JSONObject watermark = json.getJSONObject("watermark");
            return appId.equals(watermark.getString("appid"));
        } catch (Exception e) {
            return false;
        }
    }
}